import React from 'react'
import { useLocation } from 'react-router-dom'
import logo from '../../assets/logo.jpg'
import styles from './index.module.less'
import { Form, Button, Input, Toast } from 'react-vant'
import toast from 'react-hot-toast'
import { useNavigate } from 'react-router-dom'
import axios from '../../api'
export default function Login() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const { state } = useLocation()
  const onFinish = values => {
    console.log(values)
    axios.post('/user/login', values).then(res => {
      console.log(res)
      localStorage.setItem('access_token', res.access_token)
      localStorage.setItem('refresh_token', res.refresh_token)
      localStorage.setItem('user', JSON.stringify(res.data))
      if (res.code === '1') {
        toast.success('登录成功')
        navigate('/noteClass')
      }
    })
  }
  return (
    <div className={styles.login}>
      <h1 className={styles.title}>登录</h1>
      <div className={styles['title-wrapper']}>
        <div className={styles.avatar}>
          <img src={logo} alt="" />
        </div>
        <Form
          form={form}
          onFinish={onFinish}
          footer={
            <div style={{ margin: '16px 16px 0' }}>
              <Button round nativeType='submit' type='primary' block>
                登录
              </Button>
            </div>
          }
        >
          <Form.Item
            tooltip={{
              message:
                'A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.',
            }}
            intro='确保这是唯一的用户名'
            rules={[{ required: true, message: '请填写用户名' }]}
            name='username'
            label='用户名'
            labelWidth='50px'
            initialValue={state?.username}
          >
            <Input placeholder='请输入用户名' />
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: '请填写密码' }]}
            name='password'
            label='密码'
            labelWidth='50px'
            initialValue={state?.password}
          >
            <Input placeholder='请输入密码' />
          </Form.Item>
        </Form>
      </div>
      <p className={styles['title-tip']}>
        还没有账号？<span onClick={() => navigate('/register')}>去注册</span>
      </p>
    </div>
  )
}
